package com.neusoft.lohas.modules.ivm.web.business;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.neusoft.lohas.common.config.Global;
import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.utils.DateUtils;
import com.neusoft.lohas.common.utils.IdGen;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.common.web.BaseController;
import com.neusoft.lohas.modules.ivm.entity.business.Activity;
import com.neusoft.lohas.modules.ivm.entity.business.ActivityProduct;
import com.neusoft.lohas.modules.ivm.entity.business.ActivityTime;
import com.neusoft.lohas.modules.ivm.entity.merchant.Merchant;
import com.neusoft.lohas.modules.ivm.entity.product.Product;
import com.neusoft.lohas.modules.ivm.service.business.ActivityProductService;
import com.neusoft.lohas.modules.ivm.service.business.ActivityService;
import com.neusoft.lohas.modules.ivm.service.business.ActivityTimeService;
import com.neusoft.lohas.modules.ivm.utils.MerchantUtils;
import com.neusoft.lohas.modules.ivm.service.product.ProductService;
/**
 * 活动信息Controller
 * @author Jackie.Liu
 * @version 2015-01-29
 */
@Controller
@RequestMapping(value = "${adminPath}/ivm/business/activity")
public class ActivityController extends BaseController {

	@Autowired
	private ActivityService activityService;
	@Autowired
	private ActivityTimeService activityTimeService;
	@Autowired
	private ProductService productService;
	@Autowired
	private ActivityProductService activityProductService;
	
	@ModelAttribute
	public Activity get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return activityService.get(id);
		}else{
			return new Activity();
		}
	}
	
	@RequiresPermissions("ivm:business:activity:view")
	@RequestMapping(value = {"list", ""})
	public String list(Activity activity, HttpServletRequest request, HttpServletResponse response, Model model) {
//		activity.setMerchant(super.merchant);
//        Page<Activity> page = activityService.find(new Page<Activity>(request, response), activity); 
//        model.addAttribute("page", page);
//		return "modules/ivm/business/activityList";
		return "redirect:"+Global.getAdminPath()+"/ivm/business/activity/form";
	}

	@RequiresPermissions("ivm:business:activity:view")
	@RequestMapping(value = "form")
	public String form(Activity activity, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (StringUtils.isBlank(activity.getName())) {
			activity.setMerchant(super.merchant);
		}
		DecimalFormat df = new DecimalFormat("#.00");
		boolean start = false;
		boolean starting = false;
		boolean started = false;
		if (StringUtils.isBlank(activity.getId())) {
			activity.setType("1");
			Page<Activity> page = activityService.find(new Page<Activity>(request, response), activity); 
			if(page.getList().size()>0)
			activity = page.getList().get(0);
		}
		if(StringUtils.isNotBlank(activity.getId())){
			//系统当前时间
			String nowTime = DateUtils.getDate("yyyy/MM/dd HH:mm");
			Date now = new Date(nowTime);
			for(ActivityTime activityTime:activity.getTimeList()){
				Date beginTime = new Date(DateUtils.formatDate(activityTime.getActivityDate(), "yyyy/MM/dd")+" "+activityTime.getStartTime());
				Date endTime = new Date(DateUtils.formatDate(activityTime.getActivityDate(), "yyyy/MM/dd")+" "+activityTime.getEndTime());
				if(beginTime.after(now)){//即将开始
					activityTime.setState(1);
					start=true;
				}else {
					//计算抢空比
					float proportion = 0;
					//该条记录拥有的商品总量
					int numTotal = 0;
					//已抢购的总量
					int buyNumTotal = 0;
					for(ActivityProduct activityProduct:activityTime.getProductList()){
						numTotal += activityProduct.getNumber();
						buyNumTotal += activityProduct.getBuyNumber();
					}
					if(numTotal != 0){
						proportion = (float) (buyNumTotal*100/(numTotal*1.0));
						proportion = Float.parseFloat(df.format(proportion));
					}
					activityTime.setRatio(proportion);
					if(now.after(endTime)){//已结束
						activityTime.setState(3);
						started=true;
					}else{//正在进行
						activityTime.setState(2);
						starting=true;
					}
				}
			}
		}
		model.addAttribute("activity", activity);
		model.addAttribute("start", start);
		model.addAttribute("starting", starting);
		model.addAttribute("started", started);
		return "modules/ivm/business/activityForm";
	}

	@RequiresPermissions("ivm:business:activity:edit")
	@RequestMapping(value = "save")
	public String save(Activity activity, String oldName, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, activity)){
			return form(activity, request, response, model);
		}
		if (!"true".equals(checkName(oldName, activity.getName()))){
			addMessage(model, "保存活动'" + activity.getName() + "'失败，商品名已存在");
			return form(activity, request, response, model);
		}
		if (StringUtils.isBlank(activity.getId())) {
			activity.setId(IdGen.uuid());
			activity.prePersist();
		}
		for (ActivityTime time : activity.getTimeList()) {
			if (StringUtils.isBlank(time.getId())) {
				time.setActivity(activity);
				time.setId(IdGen.uuid());
				time.prePersist();
			}
		}
		activityService.save(activity);
		addMessage(redirectAttributes, "保存活动'" + activity.getName() + "'成功");
		return "redirect:"+Global.getAdminPath()+"/ivm/business/activity/form?repage";
	}
	
	@RequiresPermissions("ivm:business:activity:edit")
	@RequestMapping(value = "delete")
	public String delete(String id, RedirectAttributes redirectAttributes) {
		activityService.delete(id);
		addMessage(redirectAttributes, "删除活动成功");
		return "redirect:"+Global.getAdminPath()+"/ivm/business/activity/?repage";
	}
	
	@ResponseBody
	@RequiresPermissions("ivm:business:activity:edit")
	@RequestMapping(value = "checkName")
	public String checkName(String oldName, String name) {
		if (name !=null && name.equals(oldName)) {
			return "true";
		} else if (name !=null && activityService.getActivityByName(MerchantUtils.getMerchant().getId(), name) == null) {
			return "true";
		}
		return "false";
	}
	
	/**
	 * 获取抢购活动时间对应的抢购商品列表
	 * @param merchantId
	 * @param activityId
	 * @param timeId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "productList")
	public String productList(String merchantId, String activityId, String timeId, HttpServletRequest request, HttpServletResponse response, Model model) {
		Activity activity = new Activity(activityId);
		activity.setMerchant(new Merchant(merchantId));
		ActivityTime activityTime = new ActivityTime(timeId);
		activityTime = activityTimeService.get(timeId);
        model.addAttribute("activity", activity);
        model.addAttribute("activityTime", activityTime);
        return "modules/ivm/business/activityProduct";
	}
	
	/**
	 * 获取抢购活动时间对应的抢购商品列表(列表只读)
	 * @param merchantId
	 * @param activityId
	 * @param timeId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "productListshow")
	public String productListShow(String merchantId, String activityId, String timeId,
			@RequestParam(value="searchParam", required=false, defaultValue="") String searchParam,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Activity activity = new Activity(activityId);
		activity.setMerchant(new Merchant(merchantId));
		ActivityTime activityTime = new ActivityTime(timeId);
		activityTime = activityTimeService.get(timeId);
		ActivityProduct activityProduct = new ActivityProduct();
		activityProduct.setMerchant(activity.getMerchant());
		activityProduct.setActivity(activity);
		activityProduct.setActivityTime(activityTime);
		List<ActivityProduct> productList = activityProductService.findList(activityProduct,searchParam); 
		//封装售出比例
		DecimalFormat df = new DecimalFormat("#.00");
		for(ActivityProduct actProduct:productList){
			int number = actProduct.getNumber(); //拥有数量
			int buyNum = actProduct.getBuyNumber(); //售出数量
			float ratio = 0; //售出比例
			if(number != 0){
				ratio = (float) (buyNum*100/(number*1.0));
			}
			ratio = Float.parseFloat(df.format(ratio));
			actProduct.setRatio(ratio);
		}
		activityTime.setProductList(productList);
        model.addAttribute("activity", activity);
        model.addAttribute("activityTime", activityTime);
        model.addAttribute("searchParam", searchParam);
        model.addAttribute("timeId", timeId);
        return "modules/ivm/business/activityProductShow";
	}
	
	/**
	 * 抢购活动商品创建初始化
	 * @param merchantId
	 * @param activityId
	 * @param timeId
	 * @param code
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "productList/create")
	public @ResponseBody 
		Object createActivityProduct(String merchantId, String activityId, String timeId, String code, HttpServletRequest request, HttpServletResponse response, Model model) {
		Product product = productService.getProductByCode(merchantId, String.valueOf(code));
		ActivityProduct activityProduct = new ActivityProduct();
		activityProduct.setMerchant(new Merchant(merchantId));
		activityProduct.setActivity(new Activity(activityId));
		activityProduct.setActivityTime(new ActivityTime(timeId));
		activityProduct.setProduct(product);
		activityProduct.setPrice(product.getPrice());
		//保存活动抢购商品
		activityProductService.save(activityProduct);
		return getStatusBean(200, "添加抢购商品成功");
	}
	
	/**
	 * 保存活动抢购商品信息
	 * @param activity
	 * @param activityTime
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "productList/save")
	public String saveActivityProduct(String merchantId, String activityId, ActivityTime activityTime, Model model, RedirectAttributes redirectAttributes) {
		ActivityTime oldActivityTime = activityTimeService.get(activityTime.getId());
		for (ActivityProduct obean : oldActivityTime.getProductList()) {
			for (ActivityProduct nBean : activityTime.getProductList()) {
				if (nBean.getId().equals(obean.getId())) {
					obean.setPrice(nBean.getPrice());
					obean.setNumber(nBean.getNumber());
					obean.setSort(nBean.getSort());
					break;
				}
			}
		}
		activityTimeService.save(oldActivityTime);
		addMessage(redirectAttributes, "保存活动抢购商品成功");
		redirectAttributes.addFlashAttribute("close", true);
		return "redirect:"+Global.getAdminPath()+"/ivm/business/activity/productList?merchantId="+merchantId+"&activityId="+activityId+"&timeId="+activityTime.getId();
	}
	
	/**
	 * 删除抢购商品
	 * @param id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "productList/delete")
	public String deleteActivityProduct(String id, String merchantId, String activityId, String timeId, RedirectAttributes redirectAttributes) {
		activityProductService.delete(id);
		addMessage(redirectAttributes, "删除抢购商品成功");
		return "redirect:"+Global.getAdminPath()+"/ivm/business/activity/productList?merchantId="+merchantId+"&activityId="+activityId+"&timeId="+timeId;
	}
	
	/**
	 * 删除已结束的活动
	 */
	@RequestMapping(value = "delActivityTime")
	public @ResponseBody Object delActivityTime(String timeId, HttpServletRequest request, HttpServletResponse response){
		activityTimeService.delete(timeId);
		return getStatusBean(200, "操作成功");
	}
}
